#!/bin/bash
scriptWorkd=$(cd "$(dirname $0)";pwd)

### ========= 全局变量 ===========
n_desktop="Desktop"
n_downloads="Downloads"
n_documents="Documents"
n_public="Public"
filename="${HOME}/.config/user-dirs.dirs"
### ==============================

### ========= 前置文件 ===========
if [[ -f ${HOME}/bin/basic_func.sh ]];then  ### 存在才载入
    source ${HOME}/bin/basic_func.sh
elif [[ -f ${scriptWorkd}/../bin/basic_func.sh ]];then
    source ${scriptWorkd}/../bin/basic_func.sh
elif [[ -f ./bin/basic_func.sh ]];then
    source ./bin/basic_func.sh
fi
### ==============================

function renameDir() {
    cd ${HOME}
    mv 桌面 $n_desktop
    mv 下载 $n_downloads
    mv 文档 $n_documents
    mv 公共的 $n_public

}

function editConf() {
    sed -i "s/桌面/${n_desktop}/" ${filename}
    sed -i "s/下载/${n_downloads}/" ${filename}
    sed -i "s/文档/${n_documents}/" ${filename}
    sed -i "s/公共的/${n_public}/" ${filename}
}

function validate() {
    dirs=($(awk -F '["=]' '!/^#/ && /XDG/ {print $3}'  $filename))
    envs=($(awk -F '["=/]' '!/^#/ && /XDG/ {print $1}' $filename))
    flag=$((0))
    for i in ${!dirs[@]};   ### 加!类似python的enumerate
    do 
        tempdir=${dirs[$i]//\$HOME/$HOME}
        tempdir=${tempdir//\$\{HOME\}/$HOME}
        tempenv=${envs[$1]}
        # echo ${tempenv}
        tempenv="${tempenv#XDG_}"
        tempenv="${tempenv%_DIR}"
        # echo ${tempenv}
        if [[ ! -e "${tempdir}" ]];then
            # echo -e "${tempenv}对应的目录\e[31;1m ${dirs[$i]}\e[0m\t不存在"
            printf "${hintStrWarning}${tempenv} 对应的目录\e[31;1m %-20s \e[0m\t不存在\n" ${dirs[$i]}
        else
            printf "${hintStrOK}${tempenv} 对应的目录\e[32;1m %-20s \e[0m\t存在\n" ${dirs[$i]}
        fi
        flag=$((1))
        # echo ${envs[$i]}, ${dirs[$i]}
    done
    
    if [[ $flag == 0 ]]; then
        echo -e "\e[32;1m文件夹存在\e[0m"
    fi
}

function main() {
    ## 开始信息
    echo -e "${blue4}\n$(basename $0)\n${normal}"

    renameDir
    editConf
    validate
    echo -e "${hintStrSuccess}\nUser folders name changed\n用户目录已改为英文${normal}\n"

    ## 结束信息
    echo -e "${green4}\n$(basename $0)\n${normal}"
}
main $@
